﻿using System.Linq;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Controllers;
using Autofac;
using Autofac.Integration.WebApi;
using Autofac.Integration.WebApi.Owin;
using Inovout.Component;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup(typeof(Inovout.Web.Http.WebApiApplication))]
namespace Inovout.Web.Http
{
    public class WebApiApplication : WebApplication
    {
        private HttpConfiguration config;
        public WebApiApplication()
        {
            this.config = new HttpConfiguration();
        }
        protected override void ConfigurationApplication(IAppBuilder app)
        {

            // app.UseAutofacWebApi(config);
            //Autofac WebApi Owin 找不到任何类。
            if (!config.MessageHandlers.OfType<DependencyScopeHandler>().Any())
                config.MessageHandlers.Insert(0, new DependencyScopeHandler());
            config.Formatters.Insert(0, new JsonNetMediaTypeFormatter());

            app.UseWebApi(config);
        }
        protected override void RegisterWebComponents(ContainerBuilder builder, Assembly[] moduleAssemblies)
        {
            builder.Register(c => new MergedParameterControllerActionInvoker()).As<IHttpActionInvoker>().SingleInstance();
            builder.RegisterApiControllers(moduleAssemblies);
        }

        protected override void RegisterDependencyResolver(Autofac.ILifetimeScope container)
        {
            var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container);
            config.DependencyResolver = autofacWebApiDependencyResolver;
            ComponentRegistry.SetApplicationComponentResolver(new WebApiComponentResolver(autofacWebApiDependencyResolver));
        }
        protected override void RegisterFilters()
        {
            config.Filters.Add(new UnhandledExceptionFilter());
        }
        protected override void ConfiguationAuthentication(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            base.ConfiguationAuthentication(app);
        }
        protected override void RegisterRoutes()
        {
            config.MapHttpAttributeRoutes();

            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //    );
        }
    }
}